'use strict';
AKONG.require(['config', 'ua', 'query', 'req', 'others', 'Loading', 'AutoPlay'], function(config, ua, query, req, others, Loading, AutoPlay) {
	//diy面板
	var $diy_panel_header_li = $('.diy_panel_header>li'),
		$diy_panel_model_div = $('.diy_panel_model').children(),
		diy_panel_index = 0;

	//svg部分
	var load_svg = document.getElementsByClassName("load_svg")[0],
		svgPath = 'models/15-MC02072/',
		svgName = '1.svg',
		ns = 'http://www.w3.org/2000/svg',
		xl = 'http://www.w3.org/1999/xlink',
		svg,
		cur = {
			colorList: null,
			svgData: null
		},
		svgData = [],
		imageData = [],
		imageIndex = 0,
		mouse = {
			x: 0,
			y: 0
		},
		dataMouse = {},
		isDown = false;
	var $diy_dialog = $('.diy_dialog'),
		$diy_dialog_c = $diy_dialog.children(),
		$diy_panel_name = $('.diy_panel_name'),
		$diy_panel_color = $('.diy_panel_color'),
		$diy_svgs = $('.diy_svgs'),
		$color_title = $('.color_title'),
		$colors_ul = $('.colors_ul'),
		$diy_svgs_colors = $('.diy_svgs_colors'),
		$diy_svgs_tab_li = $('.diy_svgs_tab').children(),
		$diy_svgs_divs = $('.diy_svgs_div').children(),
		$image_list = $('.image_list'),
		$name_c,
		$color_c,
		diy_panel_name_index,
		diy_panel_color_index,
		svgs_tab_index = 0;
	window.svgData = svgData;

	function initSvg() {
		$.ajax({
			url: svgPath + svgName,
			dataType: 'text',
			success: function(result) {
				load_svg.innerHTML = result;
				svg = $(load_svg).children()[0];
				canvasToSvg(initThree);
			},
			error: function(e) {
				alert(e);
			}
		});
	}

	function initEvent() { //加载所有东西开始玩
		$diy_panel_header_li.on('click', function() {
			var i = $(this).index();
			if(i === diy_panel_index) {
				return;
			}
			diy_panel_index = i;
			$diy_panel_header_li.eq(i).addClass('active');
			$diy_panel_header_li.eq(1 - i).removeClass('active');

			$diy_panel_model_div.eq(i).removeClass('hide');
			$diy_panel_model_div.eq(1 - i).addClass('hide');

			$diy_dialog.removeClass('active0');
			$diy_dialog.removeClass('active1');
			if(diy_panel_index === 0) {
				if(typeof diy_panel_name_index === 'number') {
					$diy_dialog.addClass('active0');
				}
			} else {
				if(typeof diy_panel_color_index === 'number') {
					$diy_dialog.addClass('active1');
				}
			}
		});

		//名称模式
		(function() {
			var html = '',
				$parts = $('.load_svg [data-name^="part-"]');
			$parts.each(function(i) {
				var name = this.getAttribute('data-name').split('-')[1];
				html += '<li data-name="part-' + name + '">' + name + '</li>';
			});
			$diy_panel_name.html(html);

			html = '';
			$parts.each(function(i) {
				var name = this.getAttribute('data-name').split('-')[1],
					g = this,
					clip = $(g).children()[0],
					box = clip.getBBox(),
					g = this.cloneNode(true);

				svgData.push({
					box: box,
					name: name,
					scale: 1 || Math.max(box.width, box.height) / 340
				});
				//				g.removeAttributeNS(ns, 'clip-path');
				html += '<div class="hide"><svg width="100%" height="100%" viewBox="' + box.x + ' ' + box.y + ' ' + box.width + ' ' + box.height + '">' + g.outerHTML + '</svg></div>';
			});
			$diy_svgs.html(html);
			$diy_svgs.children().each(function(i) {
				svgData[i].svg = $(this).children()[0];
			});

			$name_c = $diy_panel_name.children();
			$name_c.on('click', function() {
				var i = $(this).index(),
					preIndex = diy_panel_name_index;
				if(preIndex === i) {
					return;
				}
				if(typeof preIndex === 'number') {
					$name_c.eq(preIndex).removeClass('active');
					$diy_svgs.children().eq(preIndex).addClass('hide');
				}
				diy_panel_name_index = i;
				$(this).addClass('active');
				$diy_dialog.addClass('active0');
				$diy_svgs.children().eq(diy_panel_name_index).removeClass('hide');
				cur.svgData = svgData[diy_panel_name_index];

				winResize();
			});
		})();

		//颜色模式
		(function(l) {
			//选色卡
			var html = '';
			for(var i = 0, step = 1 / l; i <= l; i++) {
				var rgb = hslToRgb(i * step, 1, 0.5),
					color = 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')';
				html += '<li data-color="' + color + '" style="background-color:' + color + '"></li>';
			}
			for(var i = 0, step = 1 / 10; i < 10; i++) {
				var w = 255 * i * step >> 0,
					color = 'rgb(' + w + ',' + w + ',' + w + ')';
				html += '<li data-color="' + color + '" style="background-color:' + color + '"></li>';
			}
			$colors_ul.html(html);
			$diy_svgs_colors.html(html);

			//颜色选择（部位）
			$colors_ul.children().each(function(i) {
				var color = this.getAttribute('data-color');
				$(this).on('click', function(i) {
					if(cur.colorList) {
						$color_title.attr('data-name', 'color-' + color);
						$color_title.children().css('background-color', color);
						$color_c.eq(diy_panel_color_index).html($color_title.html());
						cur.colorList.each(function() {
							this.style.fill = color;
							this.setAttributeNS(null, 'fill', color);
						});
						canvasToSvg();
					}
				});
			});

			var colorObj = {};
			html = '';
			$('.load_svg [data-name^="color-"]').each(function(i) {
				var name = this.getAttribute('data-name').split('-')[1],
					color = $(this).css('fill');
				//				console.log($(this).css('fill'));
				//				console.log(this);
				//.getAttribute('fill')
				if(!colorObj[name]) {
					colorObj[name] = true;
					html += '<li data-name="color-' + name + '">颜色' + name + '<div class="color_div" style="background-color:' + color + ';"></div></li>';
				}
			});
			$diy_panel_color.html(html);

			$color_c = $diy_panel_color.children();
			$color_c.on('click', function() {
				var i = $(this).index(),
					preIndex = diy_panel_color_index;
				if(preIndex === i) {
					return;
				}
				if(typeof preIndex === 'number') {
					$color_c.eq(preIndex).removeClass('active');
				}
				diy_panel_color_index = i;
				$(this).addClass('active');
				$diy_dialog.addClass('active1');

				var color = $(this).attr('data-name');
				$color_title.html(this.innerHTML);
				cur.colorList = $('.load_svg [data-name="' + color + '"]');
			});
		})(69);

		$diy_svgs_tab_li.on('click', function() {
			var i = $(this).index();
			if(i === svgs_tab_index) {
				return;
			}
			$diy_svgs_divs.eq(svgs_tab_index).addClass('hide');
			svgs_tab_index = i;
			$diy_svgs_divs.eq(svgs_tab_index).removeClass('hide');
		});
		//上传图片
		$('#file_input').on('change', function() {
			var fs = this.files;
			if(fs) {
				for(var i = 0, l = fs.length; i < l; i++) {
					(function(f) {
						var src = URL.createObjectURL(f);
						$image_list.prepend('<li style="background-image:url(' + src + ')" data-src="' + src + '"></li>');
					})(fs[i]);
				}
			}
		});
		//选择图片
		$image_list.on('click', function(e) {
			var that = e.target,
				src = that.getAttribute('data-src');
			cur.svgData && src && addImage(src);
		});
		//添加编辑功能
		function addEdit(contain, type) {
			if(type === 0) {
				var image = contain.getElementsByTagName('image')[0],
					editBox = contain.getElementsByTagName('svg')[0],
					btns = contain.querySelectorAll('[data-type]'),
					box = image.getBBox(),
					box2 = btns[2].getBBox(),
					index = imageIndex,
					dataObj = {
						contain: contain,
						image: image,
						editBox: editBox,
						type: '',
						center: {
							x: box.x + box.width / 2,
							y: box.y + box.height / 2
						},
						width: box.width,
						height: box.height,
						aspect: box.width / box.height,
						rotate: 0,
						offsetRotate: 0,
						x: box.x,
						y: box.y,
						translateX: 0,
						translateY: 0,
						scaleDistance: 0,
						sceneScale:cur.svgData.scale
					};
				//				dataObj.offsetRotate = Math.atan(1 / dataObj.aspect) / Math.PI * 180;
				dataObj.offsetRotate = Math.atan2(box2.y + box2.height / 2 - box.y - box.height / 2, box2.x + box2.width / 2 - box.x - box.width / 2) * 180 / Math.PI >> 0;
				imageData.push(dataObj);
				contain.addEventListener('mousedown', function(e) {
					e.preventDefault();
					this.setAttribute('class', 'contain active');
					getMouse(e, index, 'translate');
				});
				Array.prototype.slice.call(btns).forEach(function(v, i) {
					var type = v.getAttribute('data-type');
					v.addEventListener('mousedown', function(e) {
						e.stopPropagation();
						e.preventDefault();
						getMouse(e, index, type);
					});
				});
				imageIndex++;
			} else {

			}
		}

		function getMouse(e, index, type) {
			isDown = true;
			mouse.x = e.pageX;
			mouse.y = e.pageY;
			cur.imageData = imageData[index];
			cur.imageData.type = type;
			if(type === 'delete') {
				return;
			} else if(type === 'copy') {
				return;
			}
			cur.imageData.scaleDistance = Math.sqrt(Math.pow(e.pageX - cur.imageData.center.x, 2) + Math.pow(e.pageY - cur.imageData.center.y, 2)) >> 0;
			copyObj(cur.imageData, dataMouse);
		}

		function copyObj(oldObj, newObj) {
			for(var i in oldObj) {
				newObj[i] = oldObj[i];
			}
		}
		//添加图片
		function addImage(src) {
			var image = new Image(),
				end = function() {
					var curSvg = cur.svgData.svg,
						curScale = cur.svgData.scale,
						curBox = cur.svgData.box,
						g = document.createElementNS(ns, 'g'),
						w = this.width,
						h = this.height,
						s = w / h,
						state = curBox.width > curBox.height,
						imgx, imgy,
						imgw, imgh,
						w2 = 26 * curScale;
					if(state) {
						imgw = curBox.width / 2;
						imgh = imgw / s;
					} else {
						imgw = curBox.height / 2;
						imgh = imgw / s;
					}
					imgx = curBox.x + (curBox.width - imgw) / 2;
					imgy = curBox.y + (curBox.height - imgh) / 2;
					
					imgw = w;
					imgh = h;
					
//					console.log(curScale);
					g.setAttribute('class', 'svg_contain');
					g.innerHTML = '<image xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="' + src + '" x="' + imgx + '" y="' + imgy + '" width="' + imgw + '" height="' + imgh + '"></image><svg class="svg_edit" x="' + imgx + '" y="' + imgy + '" width="' + imgw + '" height="' + imgh + '"><rect width="100%" height="100%" fill="none" stroke="none"></rect>' +
						'<image width="'+w2+'" height="'+w2+'" x="-'+w2+'" y="-'+w2+'" data-type="delete" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="images/index/btn_4.png"></image>' +
						'<image width="'+w2+'" height="'+w2+'" x="100%" y="-'+w2+'" data-type="scale" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="images/index/btn_5.png"></image>' +
						'<image width="'+w2+'" height="'+w2+'" x="100%" y="100%" data-type="rotate" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="images/index/btn_6.png"></image>' +
						'<image width="'+w2+'" height="'+w2+'" x="-'+w2+'" y="100%" data-type="copy" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="images/index/btn_7.png"></image>' +
						'</svg>';

					console.log(curSvg);
					curSvg.appendChild(g);
					addEdit(g, 0);
					updateSvg();
				};
			image.src = src;
			if(image.complete) {
				end.call(image);
			} else {
				image.onload = end;
			}
		}
		document.body.addEventListener('mousemove', function(e) {
			if(isDown) {
				if(cur.imageData.type) {
					var ox, oy, w, h,s = cur.imageData.sceneScale;
					switch(cur.imageData.type) {
						case 'rotate':
							var rotate = Math.atan2(e.pageY - dataMouse.center.y, e.pageX - dataMouse.center.x) * 180 / Math.PI;
							cur.imageData.rotate = rotate - dataMouse.offsetRotate;
							console.log(rotate >> 0);
							break;
						case 'scale':
							var distance = Math.sqrt(Math.pow(e.pageX - dataMouse.center.x, 2) + Math.pow(e.pageY - dataMouse.center.y, 2)) >> 0,
								offsetDistance = distance - cur.imageData.scaleDistance,
								radian = Math.atan2(e.pageY - dataMouse.center.y, e.pageX - dataMouse.center.x) - (cur.imageData.rotate) / 180 * Math.PI;
							//								console.log(distance - cur.imageData.scaleDistance);
							ox = offsetDistance * Math.cos(radian) * 2 >> 0;
							oy = -offsetDistance * Math.sin(radian) * 2 >> 0;
							w = dataMouse.width + ox;
							h = dataMouse.height + oy;
							//								console.log(ox,oy);
							break;
						default:
							cur.imageData.translateX = dataMouse.translateX + (e.pageX - mouse.x) * s;
							cur.imageData.translateY = dataMouse.translateY + (e.pageY - mouse.y) * s;
							break;
					}
					if(cur.imageData.type === 'scale') {
						if(w / h > cur.imageData.aspect) {
							w = h * cur.imageData.aspect;
						} else {
							h = w / cur.imageData.aspect;
						}
						cur.imageData.width = w;
						cur.imageData.height = h;
						cur.imageData.width = Math.max(0, w);
						cur.imageData.height = Math.max(0, h);
						var x = cur.imageData.x + (dataMouse.width - cur.imageData.width) / 2,
							y = cur.imageData.y + (dataMouse.height - cur.imageData.height) / 2;
						cur.imageData.image.setAttribute('x', x);
						cur.imageData.image.setAttribute('y', y);
						cur.imageData.editBox.setAttribute('x', x);
						cur.imageData.editBox.setAttribute('y', y);

						cur.imageData.image.setAttribute('width', cur.imageData.width);
						cur.imageData.image.setAttribute('height', cur.imageData.height);
						cur.imageData.editBox.setAttribute('width', cur.imageData.width);
						cur.imageData.editBox.setAttribute('height', cur.imageData.height);
						cur.imageData.contain.setAttribute('transform', 'rotate(' + cur.imageData.rotate + ',' + dataMouse.center.x + ',' + dataMouse.center.y + ')');
					} else {
						cur.imageData.contain.setAttribute('transform', 'translate(' + cur.imageData.translateX + ',' + cur.imageData.translateY + ') rotate(' + cur.imageData.rotate + ',' + dataMouse.center.x + ',' + dataMouse.center.y + ')');
					}
				}
			}
		});
		document.body.addEventListener('mouseup', function(e) {
			if(isDown) {
				isDown = false;
				if(cur.imageData.type) {
					if(cur.imageData.type === 'scale') {
						var box = cur.imageData.image.getBBox();
						cur.imageData.x = box.x;
						cur.imageData.y = box.y;
					} else if(cur.imageData.type === 'rotate') {
						//cur.contain.setAttribute('transform', 'rotate(' + cur.imageData.rotate + ',' + cur.imageData.center.x + ',' + cur.imageData.center.y + ')');
					} else if(cur.imageData.type === 'translate') {
						cur.imageData.x += cur.imageData.translateX;
						cur.imageData.y += cur.imageData.translateY;
						cur.imageData.image.setAttribute('x', cur.imageData.x);
						cur.imageData.image.setAttribute('y', cur.imageData.y);
						cur.imageData.editBox.setAttribute('x', cur.imageData.x);
						cur.imageData.editBox.setAttribute('y', cur.imageData.y);
						cur.imageData.translateX = 0;
						cur.imageData.translateY = 0;

						var box = cur.imageData.image.getBBox();
						cur.imageData.center = {
							x: box.x + box.width / 2,
							y: box.y + box.height / 2
						};
						cur.imageData.contain.setAttribute('transform', 'rotate(' + cur.imageData.rotate + ',' + cur.imageData.center.x + ',' + cur.imageData.center.y + ')');
					}
					cur.imageData.type = '';
				}
			} else if(cur.data && cur.imageData.type === '') {
				cur.imageData.contain.setAttribute('class', 'contain');
			}
		});

		//else
		$(window).on('resize', winResize);
		winResize();
	}

	function updateSvg() {

	}

	//canvas纹理部分
	var canvas0 = document.getElementsByClassName("canvas0")[0];

	function canvasToSvg(callback) {
		canvg(canvas0, svg.outerHTML, {
			ignoreClear: true,
			ignoreMouse: true,
			renderCallback: function() {
				canvasTexture && (canvasTexture.needsUpdate = true) && render();
				callback && callback();
			}
		});
	}

	//3d部分
	var scene, camera, renderer, controls, group, mesh, canvasTexture, raycaster, mouse;
	var game_3d = document.getElementsByClassName("game_3d")[0],
		sceneWidth = game_3d.offsetWidth,
		sceneHeight = game_3d.offsetHeight - 100,
		game_3d_offset,
		backgroundColor = 0x252b39,
		is_controls = false;

	function winResize() {
		game_3d_offset = others.getOffset(game_3d);
	}

	function initThree(callback) {
		scene = new THREE.Scene();
		group = new THREE.Group();
		scene.add(group);

		camera = new THREE.PerspectiveCamera(75, sceneWidth / sceneHeight, 1, 10000);
		scene.add(camera);

		renderer = new THREE.WebGLRenderer({
			antialias: true
		});
		renderer.setClearColor(backgroundColor);
		renderer.setPixelRatio(window.devicePixelRatio);
		renderer.setSize(sceneWidth, sceneHeight);
		game_3d.appendChild(renderer.domElement);

		//light
		scene.add(new THREE.AmbientLight(0x444444));
		var light = new THREE.DirectionalLight(0xffffff);
		light.position.set(1, 1, 1);
		camera.add(light);

		//mesh
		var objLoader = new THREE.OBJLoader();
		objLoader.load('models/15-MC02072/1.obj', function(object) {
			mesh = object;
			mesh.scale.set(0.2, 0.2, 0.2);

			var box = new THREE.Box3();
			box.setFromObject(object);
			object.position.sub(box.getCenter());
			camera.position.z = box.getSize().z * 2.5;

			canvasTexture = new THREE.CanvasTexture(canvas0);
			var material = new THREE.MeshPhongMaterial({
				side: THREE.DoubleSide,
				map: canvasTexture
			});
			mesh.traverse(function(child) {
				if(child instanceof THREE.Mesh) {
					child.material = material;
				}
			});
			scene.add(mesh);

			render();
			initEvent();
		});

		mouse = new THREE.Vector2();
		raycaster = new THREE.Raycaster();
		controls = new THREE.OrbitControls(camera, game_3d);
		controls.enableZoom = false;
		controls.minPolarAngle = controls.maxPolarAngle = Math.PI / 2;

		controls.addEventListener('change', function() {
			is_controls = true;
			render();
		});
		game_3d.addEventListener('mouseup', function(e) {
			if(!is_controls) {
				mouse.x = ((e.pageX - game_3d_offset.left) / sceneWidth) * 2 - 1;
				mouse.y = -((e.pageY - game_3d_offset.top) / sceneHeight) * 2 + 1;
				raycaster.setFromCamera(mouse, camera);
				var intersects = raycaster.intersectObjects(mesh.children);
				if(intersects.length) {
					var object = intersects[0].object,
						name = object.name;
					$('.diy_panel_name li[data-name="part-' + name + '"]').trigger('click', true);
					//					console.log(name);
				}
			} else {
				is_controls = false;
			}
		});
	}

	function render() {
		renderer.render(scene, camera);
	}

	//加载
	var loader = new Loading();

	function init() { //主入口
		initSvg();
	}
	loader.init({
		callback: function() {
			init();
		}
	});

	//推荐设计
	var auto = new AutoPlay();
	auto.init({
		scene: query.className('designs_auto')[0],
		callback: function() {

		}
	});
	query.className('left_btn')[0].on('click', function() {
		auto.prev();
	});
	query.className('right_btn')[0].on('click', function() {
		auto.next();
	});
});